﻿function AzureTableFilterExpressionInput() {

    var self = this;

    var filter = ko.observable('');

    var expression = ko.observable(null);

    var errorMessage = ko.observable(null);

    var invalid = ko.observable(false);

    ko.computed(function () {
        var f = filter();
        if (utils.isNullOrWhiteSpace(f)) {
            expression(null);
            invalid(false);
            errorMessage(null);
            return;
        }
        try {
            var res = new AzureTableFilterExpressionParser().parseQuery(f);
            var expr = res.expression;
            expression(expr);

            var errors = res.errors;
            if (errors.length == 0) {
                invalid(false);
                errorMessage(null);
            } else {
                invalid(true);
                var msg = '';
                for (var i = 0; i < errors.length; i++) {
                    if (i > 0) msg += '\r\n';
                    msg += errors[i];
                }
                errorMessage(msg);
            }
        } catch (e) {
            invalid(true);
            errorMessage(e.message);
            expression(null);
        }
    });

    self.filter = filter;
    self.expression = expression;
    self.errorMessage = errorMessage;
    self.invalid = invalid;
}